from selenium import webdriver
from selenium.webdriver.common.by import By
import time

class TaskManagementTest:
    def __init__(self):
        """初始化浏览器"""
        try:
            self.driver = webdriver.Edge()
            self.driver.implicitly_wait(10)
            self.driver.maximize_window()

        except Exception as e:
            print(f"❌ 浏览器启动失败: {e}")
            raise

    def login_to_system(self):
        """登录系统"""
        try:
            self.driver.get("http://127.0.0.1:8848/manage-project/login.html")

            username_input = self.driver.find_element(By.CSS_SELECTOR, '#username')
            username_input.clear()
            username_input.send_keys('13800138000')
            password_input = self.driver.find_element(By.CSS_SELECTOR, '#password')
            password_input.clear()
            password_input.send_keys('phone123')
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if not (protocol_checkbox.is_selected()):
                protocol_checkbox.click()
            # 按钮
            login_button = self.driver.find_element(By.CSS_SELECTOR, '#login-btn')
            if login_button.is_enabled():
                login_button.click()

            # 等待登录成功
            time.sleep(2)
            print("✅ 登录成功")

        except Exception as e:
            print(f"❌ 登录失败: {e}")
            raise

    def navigate_to_task_management(self):
        """导航到任务管理页面"""
        try:
            print("正在进入任务管理页面...")
            # 点击任务管理菜单
            task_menu = self.driver.find_element(By.XPATH, "//span[contains(text(), '任务管理')]")
            task_menu.click()

            # 等待页面加载
            time.sleep(1)
            print("✅ 已进入任务管理页面")

        except Exception as e:
            print(f"❌ 进入任务管理页面失败: {e}")
            raise

    def create_new_task(self, task_title, task_description="", priority="medium"):
        """创建新任务"""
        try:
            print(f"正在创建任务: {task_title}")

            # 点击新建任务按钮
            add_button = self.driver.find_element(By.CSS_SELECTOR, '#add-task-btn')
            add_button.click()

            # 等待弹窗出现
            time.sleep(1)

            # 输入任务标题
            title_input = self.driver.find_element(By.ID, "task-title")
            title_input.clear()
            title_input.send_keys(task_title)

            # 输入任务描述（如果有）
            if task_description:
                description_input = self.driver.find_element(By.ID, "task-description")
                description_input.clear()
                description_input.send_keys(task_description)

            # 选择优先级
            priority_select = self.driver.find_element(By.CSS_SELECTOR, '#task-priority')
            priority_select.click()

            # 选择具体的优先级选项
            priority_option = self.driver.find_element(By.CSS_SELECTOR, '#task-priority > option:nth-child(3)')
            priority_option.click()

            # 点击保存按钮
            save_button = self.driver.find_element(By.CSS_SELECTOR, '#task-form > div.form-actions > button.form-btn.primary')
            save_button.click()

            # 等待操作完成
            time.sleep(2)
            print(f"✅ 任务创建成功: {task_title}")

            return True

        except Exception as e:
            print(f"❌ 创建任务失败: {e}")
            return False

    def search_task(self, keyword):
        """搜索任务"""
        try:
            print(f"🔍 正在搜索任务: {keyword}")

            # 输入搜索关键词
            search_input = self.driver.find_element(By.ID, "search-input")
            search_input.clear()
            search_input.send_keys(keyword)

            # 等待搜索结果
            time.sleep(3)
            print(f"✅ 搜索完成: {keyword}")

            return True

        except Exception as e:
            print(f"❌ 搜索任务失败: {e}")
            return False

    def edit_task(self, old_title, new_title, new_description=""):
        """编辑任务"""
        try:
            print(f"✏️ 正在编辑任务: {old_title} -> {new_title}")

            # 先搜索要编辑的任务
            self.search_task(old_title)
            time.sleep(3)

            # 找到任务项并点击编辑按钮
            task_items = self.driver.find_elements(By.CLASS_NAME, "task-item")
            for item in task_items:
                if old_title in item.text:
                    edit_button = item.find_element(By.XPATH, ".//button[contains(text(), '编辑')]")
                    edit_button.click()
                    break

            # 等待编辑弹窗
            time.sleep(1)

            # 修改标题
            title_input = self.driver.find_element(By.ID, "task-title")
            title_input.clear()
            title_input.send_keys(new_title)

            # 修改描述（如果有）
            if new_description:
                description_input = self.driver.find_element(By.ID, "task-description")
                description_input.clear()
                description_input.send_keys(new_description)
            time.sleep(1)
            # 保存修改
            save_button = self.driver.find_element(By.CSS_SELECTOR, '#task-form > div.form-actions > button.form-btn.primary')
            save_button.click()

            # 等待操作完成
            time.sleep(3)
            print(f"✅ 任务编辑成功: {old_title} -> {new_title}")

            return True

        except Exception as e:
            print(f"❌ 编辑任务失败: {e}")
            return False

    def complete_task(self, task_title):
        """标记任务为完成"""
        try:
            print(f"✅ 正在标记任务为完成: {task_title}")

            # 搜索任务
            self.search_task(task_title)
            time.sleep(2)

            # 找到任务项并点击完成按钮
            task_items = self.driver.find_elements(By.CLASS_NAME, "task-item")
            for item in task_items:
                if task_title in item.text:
                    complete_button = item.find_element(By.XPATH, ".//button[contains(text(), '完成')]")
                    complete_button.click()
                    break

            # 等待操作完成
            time.sleep(2)
            print(f"✅ 任务标记为完成: {task_title}")

            return True

        except Exception as e:
            print(f"❌ 标记任务失败: {e}")
            return False

    def delete_task(self, task_title):
        """删除任务"""
        try:
            print(f"🗑️ 正在删除任务: {task_title}")

            # 搜索任务
            self.search_task(task_title)
            time.sleep(3)

            # 找到任务项并点击删除按钮
            task_items = self.driver.find_elements(By.CLASS_NAME, "task-item")
            for item in task_items:
                if task_title in item.text:
                    delete_button = item.find_element(By.XPATH, ".//button[contains(text(), '删除')]")
                    delete_button.click()
                    break

            # 处理确认对话框
            time.sleep(2)

            # 确认删除（假设有确认对话框）
            try:
                # 如果弹出确认框，点击确定
                alert = self.driver.switch_to.alert
                alert.accept()
                time.sleep(1)
                self.search_task()
            except:
                # 如果没有确认框，继续执行
                pass

            # 等待操作完成
            time.sleep(1)
            print(f"✅ 任务删除成功: {task_title}")

            return True

        except Exception as e:
            print(f"❌ 删除任务失败: {e}")
            return False

    def filter_tasks(self, filter_type, filter_value):
        """筛选任务"""
        try:
            print(f"筛选任务: {filter_type} = {filter_value}")

            if filter_type == "status":
                # 状态筛选
                status_select = self.driver.find_element(By.CSS_SELECTOR, '#filter-status')
                status_select.click()
                status_option = self.driver.find_element(By.CSS_SELECTOR, '#filter-status > option:nth-child(3)')
                status_option.click()

            elif filter_type == "priority":
                # 优先级筛选
                priority_select = self.driver.find_element(By.CSS_SELECTOR, '#filter-priority')
                priority_select.click()
                priority_option = self.driver.find_element(By.CSS_SELECTOR, '#filter-priority > option:nth-child(2)')
                priority_option.click()

            time.sleep(3)
            print(f"✅ 筛选完成: {filter_type} = {filter_value}")

            return True

        except Exception as e:
            print(f"❌ 筛选任务失败: {e}")
            return False

    def run_all_tests(self):
        """运行所有测试用例"""
        print("=" * 60)
        print("开始执行任务管理页面自动化测试")
        print("=" * 60)

        try:
            # 1. 登录系统
            self.login_to_system()

            # 2. 进入任务管理页面
            self.navigate_to_task_management()

            # 3. 创建任务测试
            print("\n1. 测试创建任务功能")
            test_tasks = [
                {"title": "学习Python自动化测试", "description": "完成Selenium学习", "priority": "high"},
                {"title": "编写测试脚本", "description": "编写任务管理测试用例", "priority": "medium"},
                {"title": "复习测试知识", "description": "复习软件测试基础知识", "priority": "low"}
            ]

            for task in test_tasks:
                success = self.create_new_task(
                    task["title"],
                    task["description"],
                    task["priority"]
                )
                if not success:
                    print("❌ 创建任务测试失败")
                    return False

            # 4. 搜索任务测试
            print("\n2. 测试搜索任务功能")
            success = self.search_task("Python")
            if not success:
                print("❌ 搜索任务测试失败")
                return False

            # 5. 编辑任务测试
            print("\n3. 测试编辑任务功能")
            success = self.edit_task(
                "编写测试脚本",
                "编写完整的测试脚本",
                "编写包含增删改查的完整测试脚本"
            )
            if not success:
                print("❌ 编辑任务测试失败")
                return False

            # 6. 完成任务测试
            print("\n4. 测试标记完成任务功能")
            success = self.complete_task("复习测试知识")
            if not success:
                print("❌ 标记完成任务测试失败")
                return False

            # 7. 筛选任务测试
            print("\n5. 测试筛选任务功能")
            success = self.filter_tasks("status", "completed")
            if not success:
                print("❌ 筛选任务测试失败")
                return False

            # 8. 删除任务测试
            print("\n6. 测试删除任务功能")
            success = self.delete_task("复习测试知识")
            if not success:
                print("❌ 删除任务测试失败")
                return False

            return True

        except Exception as e:
            print(f"\n❌ 测试执行过程中出现错误: {e}")
            return False

        finally:
            # 关闭浏览器
            self.close_browser()

    def close_browser(self):
        """关闭浏览器"""
        try:
            self.driver.quit()
        except Exception as e:
            print(f"❌ 关闭浏览器失败: {e}")


# 运行测试
if __name__ == "__main__":
    # 创建测试实例
    test = TaskManagementTest()

    # 运行所有测试
    success = test.run_all_tests()

    # 输出最终结果
    if success:
        print("\n🎉 恭喜！所有测试都通过了！")
    else:
        print("\n😞 测试执行失败，请检查错误信息")